<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="60" />
      <el-table-column label="县乡村" min-width="350">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.areaId`" :rules="formRules.areaId" class="mb-0px!">
            <!--            <el-select v-model="row.areaId" placeholder="请选择县乡村编号">
                            <el-option label="请选择字典生成" value="" />
                        </el-select>-->
            <el-tree-select
              v-if="editingRows.has($index)"
              v-model="row.areaId"
              :data="areaTree"
              :props="defaultProps"
              check-strictly
              default-expand-all
              placeholder="请选择县乡村"
            />
            <span v-else class="cursor-pointer">
              {{ getAreaLabel(row.areaId) || '点击选择' }}
            </span>
<!--
            县乡村默认只显示文本，点击事件（@click="startEdit($index)"）触发后变成编辑状态下显示下拉树形结构，否则显示文本标签，点击后触发编辑事件，编辑情况不应该修改
            <span v-else @click="startEdit($index)" class="cursor-pointer">
              {{ getAreaLabel(row.areaId) || '点击选择' }}
            </span>-->
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="户数" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.familyNum`" :rules="formRules.familyNum" class="mb-0px!">
            <el-input v-model="row.familyNum" placeholder="请输入户数" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="金额" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.amount`" :rules="formRules.amount" class="mb-0px!">
            <el-input v-model="row.amount" placeholder="请输入金额" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="余额" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.balance`" :rules="formRules.balance" class="mb-0px!">
            <el-input v-model="row.balance" placeholder="请输入余额" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加数据统计子</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { DataStatsApi } from '@/api/circ/datastats'
import { AreaApi} from '@/api/circ/area'
import { defaultProps, handleTree } from '@/utils/tree'

const props = defineProps<{
  pid: undefined // 数据统计主表id（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  pid: [{ required: true, message: '数据统计主表id不能为空', trigger: 'blur' }],
  areaId: [{ required: true, message: '县乡村编号不能为空', trigger: 'change' }],
  familyNum: [{ required: true, message: '户数不能为空', trigger: 'blur' }],
  amount: [{ required: true, message: '金额不能为空', trigger: 'blur' }],
  balance: [{ required: true, message: '余额不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const areaTree = ref() // 树形结构
const editingRows = ref(new Set()) // 正在编辑的行索引集合

/** 获取区域标签文本 */
const getAreaLabel = (areaId) => {
  //console.log('areaTree', areaTree)
  if (!areaId || !areaTree.value) return ''

  const findLabel = (nodes) => {
    for (const node of nodes) {
      if (node.id === areaId) {
        return node.name
      }
      if (node.children) {
        const found = findLabel(node.children)
        if (found) return found
      }
    }
    return null
  }

  return findLabel(areaTree.value)
}

/** 开始编辑某行 */
const startEdit = (index) => {
  editingRows.value.add(index)
}


/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.pid,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return
    }
    try {
      formLoading.value = true
      formData.value = await DataStatsApi.getDataStatsChildListByPid(val)
    } finally {
      formLoading.value = false
    }
    // 不需要每次都获取areaTree，只在组件初始化时获取一次
    // await getAreaTree()
  },
  { immediate: true }

)

/** 新增按钮操作 */
const handleAdd = async () => {
  // 确保areaTree已经加载
  if (!areaTree.value || areaTree.value.length === 0) {
    await fetchAreaTree();
  }
  const row = {
    id: undefined,
    pid: undefined,
    areaId: undefined,
    familyNum: undefined,
    amount: undefined,
    balance: undefined
  }
  row.pid = props.pid
  formData.value.push(row)
  // 新增的行默认进入编辑状态
  editingRows.value.add(formData.value.length - 1)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
  editingRows.value.delete(index)
  // 更新后续行的索引
  const newEditingRows = new Set()
  for (const rowIndex of editingRows.value) {
    if (rowIndex > index) {
      newEditingRows.add(rowIndex - 1)
    } else if (rowIndex < index) {
      newEditingRows.add(rowIndex)
    }
  }
  editingRows.value = newEditingRows
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

/** 获得县乡村树 */
// const getAreaTree = async () => {
//   areaTree.value = []
//   const data = await AreaApi.getAreaList('')
//   const root: Tree = { id: 0, name: '顶级县乡村', children: [] }
//   root.children = handleTree(data, 'id', 'parentId')
//   areaTree.value.push(root)
// }

/** 获得县乡村树 */
const getAreaTree = async () => {
  areaTree.value = []
  try {
    const data = await AreaApi.getAreaList('')
    if (!data || data.length === 0) {
      console.warn('No area data returned from server')
      return
    }
    const root: Tree = { id: 0, name: '顶级县乡村', children: [] }
    root.children = handleTree(data, 'id', 'parentId')
    areaTree.value.push(root)
  } catch (error) {
    console.error('Failed to get area tree:', error)
  }
}

// 组件初始化时获取一次区域树数据
// onMounted(async () => {
//   await getAreaTree()
// })

// 组件初始化时尝试获取区域树数据（非阻塞）
onMounted(async () => {
  await getAreaTree()
})

defineExpose({ validate, getData })
</script>
